package org.example.oop.thread;

import lombok.SneakyThrows;

/**
 * org.example.oop.thread
 *
 * @author moLei
 * @description 守护线程会在用户线程结束后结束，用户线程全部结束后，守护线程会直接中断，异常处理中的finally模块也不会进行执行
 * @since 2025/6/22
 */
public class DaemonThreadDemo {

    public static void main(String[] args) {

        // 设置守护线程
        Thread daemon = new Thread(new Runnable() {
            /**
             * @SneakyThrows注解就是忽略try catch，不用显示的声明，和手动加try catch一样
             */
            @Override
            public void run() {
                try {
                    int i = 0;
                    // 设置为死循环，
                    while (true) {
                        Thread.sleep(1000);
                        System.out.println(Thread.currentThread().getName() + "--------" + ++i);
                    }
                } catch (Exception e) {
                    System.out.println(e.getMessage());
                } finally {
                    System.out.println("daemon thread end");
                }
            }
        });
        // 设置为守护线程
        daemon.setDaemon(true);
        daemon.setName("Thread-daemon");
        daemon.start();

        Thread userThread = new Thread(new Runnable() {
            @Override
            @SneakyThrows
            public void run() {
                for (int i = 0; i < 10; i++) {
                    Thread.sleep(500);
                    System.out.println(Thread.currentThread().getName() + "-----------" + i);
                }
                System.out.println("Thread-user end");
            }
        });
        userThread.setName("Thread-user");
        userThread.start();
        // main线程结束，userThread线程结束，daemon线程结束
        System.out.println("main thread end");


    }
}
